package com.lang.downloader.http.Interceptor;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Http 访问 日志打印
 */
@Slf4j
public class HttpLogInterceptor implements Interceptor {
    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        Request request = chain.request();
        List<String> logInfoMark = new ArrayList<>();
        List<String> logInfoData = new ArrayList<>();
        String method = request.method();
        HttpUrl httpUrl = request.url();
        String requestId = UUID.randomUUID().toString();
        { //打印 请求方法、请求方式、请求链接
            logInfoMark.add("requestId={} {}  {}");
            logInfoData.add(requestId);
            logInfoData.add(method);
            logInfoData.add(httpUrl.url().toString());
        }
        Headers requestHeaders = request.headers();
        { //打印 请求头
            if (requestHeaders.size() > 0) {
                logInfoMark.add("--------------------{}--------------------");
                logInfoData.add(requestId);
                logInfoMark.add("RequestHeader:");
                requestHeaders.forEach(pair -> {
                    logInfoMark.add("{}: {}");
                    logInfoData.add(pair.getFirst());
                    logInfoData.add(pair.getSecond());
                });
                logInfoMark.add("--------------------{}--------------------");
                logInfoData.add(requestId);
            }
        }
        log.info(String.join("\n", logInfoMark), logInfoData.toArray(new Object[]{}));
        logInfoMark.clear();
        logInfoData.clear();
        Response response;
        try {
            response = chain.proceed(request);
        } catch (Exception e) {
            logInfoMark.add("ERROR---------------" + requestId + "--------------------");
            log.error("ERROR---------------" + requestId + "--------------------\n", e);
            throw e;
        }
        Headers responseHeaders = response.headers();
        { //打印 响应头
            if (responseHeaders.size() > 0) {
                logInfoMark.add("--------------------{}--------------------");
                logInfoData.add(requestId);
                logInfoMark.add("ResponseHeader:");
                responseHeaders.forEach(pair -> {
                    logInfoMark.add("{}: {}");
                    logInfoData.add(pair.getFirst());
                    logInfoData.add(pair.getSecond());
                });
                logInfoMark.add("--------------------{}--------------------");
                logInfoData.add(requestId);
            }
        }
        log.info(String.join("\n", logInfoMark), logInfoData.toArray(new Object[]{}));
        return response;
    }
}
